package com.d404.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;

import im.beans.AddNewFriends;
import im.beans.User;
import im.notify.server.Notify;
import manager.MessageManager;
import manager.PersistentManager;

/**
 * Servlet implementation class AddFriend
 */
//@WebServlet("/AddFriend")
public class AddFriend extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddFriend() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String userName = request.getParameter("userName");
		String friendName = request.getParameter("friendName");
		String userId = request.getParameter("userId");
		String message = request.getParameter("message");
		
		MsgBack back = new MsgBack();
		
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
		Session session = sf.getCurrentSession();
		
		Transaction tx = session.beginTransaction();
		try
		{
			boolean isuserExist = false;
			// 根据账号查找用户
			Query q = session.createQuery("from User u where u.account = ?");
			q.setParameter(0, friendName);

			User tempUser = null;
			// 获取所有结果
			List<User> users = q.list();
			for (User u : users) {
				isuserExist = true;
				tempUser = u;
			}
			
			if (isuserExist) {
				// 新建好友请求
				long ask_id_long = Long.parseLong(userId);
				long be_ask_id_long = tempUser.getId();
				back.setFriendId(be_ask_id_long+"");

				Query q2 = session.createQuery("from AddNewFriends anf where anf.asker_id = ? and anf.be_asked_id = ?");
				q2.setParameter(0, ask_id_long);
				q2.setParameter(1, be_ask_id_long);

				AddNewFriends newFriends = new AddNewFriends();
				newFriends.setAsker_id(ask_id_long);
				newFriends.setAsker_name(userName);
				newFriends.setBe_asked_id(be_ask_id_long);
				newFriends.setBe_asked_name(friendName);
				newFriends.setMessage(message);
				newFriends.setState(AddFriend.MsgBack.State.WAIT_TO_BE_DEALED);;
				
				
				List<AddNewFriends> anfs = q2.list();
				for (AddNewFriends add : anfs) {
					newFriends = add;
					newFriends.setMessage(message);
					newFriends.setState(AddFriend.MsgBack.State.WAIT_TO_BE_DEALED);
				}
				
				session.save(newFriends);
				back.setId(newFriends.getId()+"");
				back.setStatus(MsgBack.SUCCESS);
				
				//TODO 通知在线被接受者
				MessageManager.sendSimpleMessage(friendName, Notify.FRIEND_REQUEST);
			}else
			{
				// 用户不存在，返回不存在
				back.setStatus(MsgBack.USER_NOT_EXISTS);
			}
			
			session.getTransaction().commit();
		}catch(Exception e)
		{
			tx.rollback();
			back.setStatus(MsgBack.FAILED);
			e.printStackTrace();
			
		}finally {
		}
		
		System.out.println(JSON.toJSON(back));
		response.setCharacterEncoding("UTF-8");
		response.getWriter().append(JSON.toJSONString(back));
	}

	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	/**
	 * 返回响应
	 * @author 凯
	 *
	 */
	public static class MsgBack
	{
		public static final String USER_NOT_EXISTS = "3";
		public static final String SUCCESS = "1";
		public static final String FAILED = "2";//其他未知错误
		
		public static class State
		{
			/**
			 * 等待用户请求被处理
			 */
			public static final int WAIT_TO_BE_DEALED = 1;
			/**
			 * 用户拒绝好友请求
			 */
			public static final int USER_REFUSE = 2;
			/**
			 * 用户接受好友请求
			 */
			public static final int USER_ACCEPT = 3;
			 /**
             * 请求者已知晓，请求事务已完成
             */
            public static final int ASKER_FINISHED = 4;
		}
		
		public String status = "";
		public String friendId = "";
		public String id = "";
		
		public String getStatus() {
			return status;
		}
		public void setStatus(String status) {
			this.status = status;
		}
		public String getFriendId() {
			return friendId;
		}
		public void setFriendId(String friendId) {
			this.friendId = friendId;
		}
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		
		
	}

}
